package com.cet.programmercarl.algorithmperformancanalysis.栈与队列;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * @program: algorithm
 * @description: 逆波兰表达式
 * @author: 陈恩涛
 * @create: 2022-07-12 15:25
 **/
public class LC150 {

    public static void main(String[] args) {

    }

    public static int evalRPN(String[] tokens) {
        final Deque<Integer> deque = new ArrayDeque<>();
        for (String token : tokens) {
            if ("+".equals(token)) {
                final Integer rightValue = deque.pop();
                deque.push(deque.pop() + rightValue);
            } else if ("-".equals(token)) {
                final Integer rightValue = deque.pop();
                deque.push(deque.pop() - rightValue);
            } else if ("*".equals(token)) {
                final Integer rightValue = deque.pop();
                deque.push(deque.pop() * rightValue);
            } else if ("/".equals(token)) {
                final Integer rightValue = deque.pop();
                deque.push(deque.pop() / rightValue);
            } else {
                deque.push(Integer.valueOf(token));
            }
        }
        if (deque.size() != 1) {
            throw new RuntimeException("expression is invalid!");
        }
        return deque.pop();
    }
}
